package com.mytijian.code.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import com.alibaba.fastjson.JSON;
import com.mytijian.code.enums.CodeOperateEnum;
import com.mytijian.code.enums.WriteOffEnum;
import com.mytijian.code.enums.WriteOffIsSuccessEnum;
import com.mytijian.code.exceptions.MashangExceptionEnum;
import com.mytijian.code.model.Mcode;
import com.mytijian.code.model.MerchantOrder;
import com.mytijian.code.param.alihalt.ToTBAvailableParam;
import com.mytijian.code.param.alihalt.ToTBConsumeParam;
import com.mytijian.code.service.helper.ToTaobaoHelper;
import com.mytijian.code.service.helper.TransactionHelper;
import com.mytijian.exception.BizException;
import com.mytijian.exception.BizSystemException;
import com.mytijian.utils.BeanUtil;
import com.mytijian.utils.Lists;

/**
 * Created by shjh on 2017/9/27.
 */
@Service
public class ConsumeCodeServiceImpl implements ConsumeCodeService {
	
	private Logger logger = LoggerFactory.getLogger(ConsumeCodeServiceImpl.class);

	@Autowired
	private CodeService codeService;
	@Autowired
	private MerchantOrderService merchantOrderService;
	@Autowired
	private ToTaobaoHelper toTaobaoHelper;
	@Autowired
	private CodeOperateLogService codeOperateLogService;
	@Autowired
	private TransactionHelper transactionHelper;

	@Override
	public void consume(ToTBConsumeParam param) {
		logger.info("电子码核销开始param: {}", JSON.toJSONString(param));
		// 获取码、订单
		Mcode mcode = getCodeByCode(param.getCode());
		MerchantOrder order = getMerchantOrder(mcode.getOuterId());
		// 校验码是否可用
		available(BeanUtil.createObject(param, ToTBAvailableParam.class));
		// 核销码
		TransactionStatus status = transactionHelper.beginTransaction();
		try {
			// 添加码核销日志
			codeOperateLogService.saveCodeOperateLogs(Lists.newArrayList(mcode), CodeOperateEnum.CONSUME_CODE);
			// 核销
			localConsume(mcode.getId());
			transactionHelper.commit(status);
		} catch (Exception ex) {
			transactionHelper.rollback(status);
			throw new BizSystemException(MashangExceptionEnum.SYSTEM_ERROR, ex);
		}
		//核销
		toTaobaoHelper.consume(order, mcode.getCode(), true);
		// 核销成功
		consumeSuccess(mcode.getId());

		logger.info("电子码核销结束code={}", param.getCode());
	}

	@Override
	public void reConsume() {
		List<Mcode> mcodes = codeService.listNeedConsumeCode();
		for (Mcode mcode : mcodes) {
			logger.info("码[code={}]重新回调核销接口开始 ", mcode);
			MerchantOrder merchantOrder = merchantOrderService.getOrderByOuterId(mcode.getOuterId());
			if (merchantOrder != null) {
				// 核销
				toTaobaoHelper.consume(merchantOrder, mcode.getCode(), false);
				// 核销成功
				consumeSuccess(mcode.getId());
			}
			logger.info("码[code={}]重新回调核销接口结束 ", mcode);
		}

	}

	@Override
	public void available(ToTBAvailableParam param) {
		logger.info("电子码核销校验接口param: {}", JSON.toJSONString(param));

		Mcode code = getCodeByCode(param.getCode());
		MerchantOrder order = getMerchantOrder(code.getOuterId());
		//校验码是否可用
		toTaobaoHelper.available(param.getCode(), order);

		logger.info("电子码核销校验接口结束");
	}

	private MerchantOrder getMerchantOrder(String outerId) {

		MerchantOrder merchantOrder = merchantOrderService.getOrderByOuterId(outerId);
		if (merchantOrder == null) {
			throw new BizException(MashangExceptionEnum.ORDER_NOT_EXIST);
		}
		return merchantOrder;
	}

	private Mcode getCodeByCode(String code) {
		Mcode mcode = codeService.getCodeByCode(code);
		codeService.validCode(mcode);
		return mcode;
	}

	private int consumeSuccess(Integer codeId) {
		Mcode mcode = new Mcode();
		mcode.setId(codeId);
		mcode.setWriteOffIsSuccess(WriteOffIsSuccessEnum.WRITE_OFF_SUCCESS.getCode());
		return codeService.updateMcode(mcode);
	}

	private int localConsume(Integer codeId) {
		Mcode mcode = new Mcode();
		mcode.setId(codeId);
		mcode.setWriteOffStatus(WriteOffEnum.WRITE_OFF.getCode());
		return codeService.updateMcode(mcode);
	}
}
